﻿using System;
using System.Collections.Generic;
using UniRx;

public static class RxEventBus
{
    // 存储不同类型事件的 Subject
    private static readonly Dictionary<Type, object> subjects = new Dictionary<Type, object>();

    // 发布事件
    public static void Publish<T>(T message)
    {
        lock (subjects)
        {
            if (subjects.TryGetValue(typeof(T), out object subject))
            {
                ((Subject<T>)subject).OnNext(message);
            }
        }
    }

    // 订阅事件
    public static IObservable<T> Subscribe<T>()
    {
        lock (subjects)
        {
            if (!subjects.TryGetValue(typeof(T), out object subject))
            {
                subject = new Subject<T>();
                subjects[typeof(T)] = subject;
            }

            return (IObservable<T>)subject;
        }
    }

    // 取消订阅（释放资源）
    public static void Unsubscribe<T>()
    {
        lock (subjects)
        {
            if (subjects.TryGetValue(typeof(T), out object subject))
            {
                ((Subject<T>)subject).OnCompleted();
                subjects.Remove(typeof(T));
            }
        }
    }
}